﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Threading;
using System.ComponentModel;
using WMSSoft.Lib.Basic;
using WMSSoft.Lib.Const;
using WMSSoft.Lib.Enums;
using WMSSoft.Lib.Interfaces;
using WMSSoft.Lib.Texte;
using WMSSoft.Lib.WinKStart;
using GoogleSearchAPI.Query;
using GoogleSearchAPI;
using GoogleSearchAPI.Resources;

namespace WMSSoft.WinKStart.SearchEngine
{
    public class GoogleWebSearchEngine : iWinKStartSearchEngine
    {
        private string _Name = "";
        private string _AssemblyName = "";
        private string _ShortName = "";
        private string _ClassNáme = "";
        private string _DataSource = "";
        private string _SearchPattern = "";
        long m_LastUpdate = 0;
        bool _StopThreadWork = false;
        BackgroundWorker m_BackgroundWorker = null;
        private iWinKStartItem _SearchResult = null;
        private iWinKStartItem _ThreadSearchResult = null;
        private cDataSourcesReader _DataSources = null;

        public event EventHandler SearchCompleted;

        public GoogleWebSearchEngine() 
        {
            _SearchResult = new cStartmenuItem("SEARCHRESULT", "SearchResult", eLinkExecutionTypes.Program,
                                               "", eExecutionProcedure.Unknown, eItemType.Folder, "", null,
                                               null, "", "", "", "");
        }

        #region Properties
        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }

        public string Assembly
        {
            get { return _AssemblyName; }
            set { _AssemblyName = value; }
        }

        public string ClassName
        {
            get { return _ClassNáme; }
            set { _ClassNáme = value; }
        }

        public string ShortName
        {
            get { return _ShortName; }
            set { _ShortName = value; }
        }

        public string DataSourceName
        {
            get { return _DataSource; }
            set { _DataSource = value; }
        }

        public iWinKStartItem SearchResult
        {
            get { return _SearchResult; }            
        }

        #endregion

        #region Public Methods
        public void Search(string Pattern, int DefaultItemsCount)
        {
            try 
            {
                _SearchPattern = Pattern;

                m_BackgroundWorker = new BackgroundWorker();
                m_BackgroundWorker.WorkerReportsProgress = true;
                m_BackgroundWorker.WorkerSupportsCancellation = true;
                m_BackgroundWorker.ProgressChanged += worker_ProgressChanged;
                m_BackgroundWorker.DoWork += m_BackgroundWorker_DoWork;

                m_BackgroundWorker.RunWorkerAsync();
               //Thread WebSearchThread = new Thread(ThreadMethode_WebSearch);
               // WebSearchThread.Start();
            }
            catch (Exception Ex){

            }
        }
        #endregion

        public bool StopWorking()
        {
            _StopThreadWork = true;
            m_BackgroundWorker.CancelAsync();
            return true;
        }

        #region Private Methods
        void ThreadMethode_WebSearch()
        {
            ((cStartmenuItem)_SearchResult).Clear();

            cStartmenuItem tmpSearchResult = (cStartmenuItem)_SearchResult;
            try
            {

                //m_Matc
                WebQuery query = new WebQuery(_SearchPattern);
                query.StartIndex.Value = 2;
                query.HostLangauge.Value = Languages.German;
                IGoogleResultSet<GoogleWebResult> resultSet = GoogleService.Instance.Search<GoogleWebResult>(query);                                

                for (int iResultCounter = 0; iResultCounter < resultSet.Results.Count; iResultCounter++)
                {
                    //if Thread will stop work, exit for here
                    if (_StopThreadWork == true) break;

                    cStartmenuItem tmpItem = new cStartmenuItem("Websearchresult" + iResultCounter.ToString(),
                                                                resultSet.Results[iResultCounter].TitleNoFormatting,
                                                                eLinkExecutionTypes.Program,
                                                                resultSet.Results[iResultCounter].Url,
                                                                eExecutionProcedure.Unknown,
                                                                eItemType.URL,
                                                                resultSet.Results[iResultCounter].Content,
                                                                System.Drawing.Icon.FromHandle(WMSSoft.WinKStart.SearchEngine.Google.Properties.Resources.applications_internet.GetHicon()),
                                                                ((cStartmenuItem)tmpSearchResult),
                                                                "", resultSet.Results[iResultCounter].VisibleUrl, "", "");
                    tmpItem.ContentType = eContentPanelContentType.SearchResultWeb;
                    tmpSearchResult.AddChild(tmpItem);
                    //tmpDataSourceInstance.AddChilds(tmpItem.ChildItems, ""); ;
                }

                //_SearchResult = tmpDataSourceInstance.Data;
            }
            catch (Exception Ex)
            {
                WMSSoft.Lib.Basic.CMessagelogging.AppendMessage("Error while searching on Web!", Ex, EMessageTypes.Error);
            }
                finally
            {
                m_BackgroundWorker.ReportProgress(100, tmpSearchResult);
            }
        }

        void m_BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            ThreadMethode_WebSearch();
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            m_LastUpdate = DateTime.Now.Ticks;

            _SearchResult = (cStartmenuItem)e.UserState;

            if (SearchCompleted != null) SearchCompleted(this, EventArgs.Empty);
        }
        #endregion
    }
}
